<!-- 登录 -->
<template>
  <div class="loginCnt">
    <!-- <div class="logo">
      <img src="/img/login-logo.png" alt="">
    </div> -->

    <div class="box">
      <div class="img">
        <img src="/img/login-img.png" alt="" />
      </div>

      <div class="line"></div>

      <div
        class="inputBox"
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-background="rgba(226, 229, 234, 0.23)"
      >
        <!-- <h3>深圳市宝安区<br /> 治水提质水质动态监测系统</h3> -->
        <!-- <h3>安志生态河流水质状况监测与评价系统</h3> -->
        <h3>城镇污水管网水质动态监测系统</h3>
        <!-- <h3>治水提质水质动态监测系统</h3>  -->
        <div class="input">
          <el-input
            v-model="account"
            placeholder="请输入用户名"
            width="320px"
            autofocus
            style="margin-bottom: 20px"
          ></el-input>
          <el-input
            v-model="password"
            placeholder="请输入密码"
            @keyup.enter.native="doLogin"
            show-password
          ></el-input>
          <div class="footerBtn">
            <p class="forgetPassword" @click="openForgetPwCnt">忘记密码</p>
            <p class="forgetPassword" @click="added">申请账号</p>
          </div>
          <p class="loginBtn" @click="doLogin">登录</p>
        </div>
      </div>
    </div>

    <div class="footer">Copyright © 2019 安志生态</div>

    <el-dialog :visible.sync="forgetPassWordVisible">
      <div slot="title">
        <p>忘记密码</p>
      </div>
      <el-form
        :model="forgetPassWordForm"
        :rules="forgetFormRules"
        ref="forgetPassWordForm"
        size="small"
        label-width="80px"
        v-loading="forgetPassWordLoading"
      >
        <el-form-item label="账号" prop="account">
          <el-input
            v-model="forgetPassWordForm.account"
            placeholder="请输入账号"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="forgetPassWordForm.phone"
            placeholder="请输入手机号"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="身份证" prop="identity">
          <el-input
            v-model="forgetPassWordForm.identity"
            placeholder="请输入身份证"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="forgetPassWordForm.newPassword"
            placeholder="请输入新密码"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="kaptcha">
          <el-input
            placeholder="请输入验证码"
            v-model="forgetPassWordForm.kaptcha"
            autocomplete="off"
          >
            <template slot="append">
              <el-button
                class="code"
                type="primary"
                v-show="show"
                @click.prevent="getCode(forgetPassWordForm.phone)"
                >获取验证码</el-button
              >
              <el-button type="info" v-show="!show"
                >{{ count }}s后重试</el-button
              >
            </template>
          </el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          class="greenBtn"
          size="mini"
          @click="subForgetPassword('forgetPassWordForm')"
          >提交</el-button
        >
      </div>
    </el-dialog>
    <el-dialog width="70%" :visible.sync="addedFormVisible">
      <div slot="title">
        <p>申请账号</p>
      </div>
      <el-form
        style="width: 80%; margin: 0 auto"
        :model="addedForm"
        :rules="addedFormRules"
        size="mini"
        ref="addedForm"
        label-width="100px"
        v-loading="addedFormLoading"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="username" label-width="80px">
              <el-input
                v-model="addedForm.username"
                placeholder="姓名"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select
                v-model="addedForm.gender"
                placeholder="请选择性别"
                style="width: 100%"
              >
                <el-option label="男" value="1"></el-option>
                <el-option label="女" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="12">
            <el-form-item label="出生年月" prop="birth" label-width="80px">
              <el-date-picker
                v-model="addedForm.birth"
                type="date"
                :clearable="false"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                placeholder="请选择出生年月">
              </el-date-picker>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="12">
            <el-form-item label="毕业院校" prop="school" >
              <el-input v-model="addedForm.school" placeholder="请填写毕业院校"></el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="角色类型" prop="roleId" label-width="80px">
              <el-select
                v-model="addedForm.roleId"
                placeholder="请选择角色类型"
                style="width: 100%"
              >
                <el-option
                  v-for="item in roleArr"
                  :key="item.id"
                  :label="item.description"
                  :value="item.id"
                ></el-option>
                <!-- <el-option label="水站管理员" value="3"></el-option>
								<el-option label="环保管理部门" value="4"></el-option> -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input
                v-model="addedForm.phone"
                placeholder="手机号"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="12">
            <el-form-item label="专业" prop="profession" label-width="80px">
              <el-input v-model="addedForm.profession" placeholder="请填写专业"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="技术职称" prop="technicalTitle" >
              <el-input v-model="addedForm.technicalTitle" placeholder="请填写技术职称"></el-input>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row>
          <!-- <el-col :span="12">
            <el-form-item label="身份证" prop="identity" label-width="80px">
              <el-input v-model="addedForm.identity" placeholder="身份证"></el-input>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="12">
            <el-form-item label="角色类型" prop="roleId">
              <el-select v-model="addedForm.roleId" placeholder="请选择角色类型" style="width: 100%">
                <el-option label="运维人员" value="2"></el-option>
                <el-option label="水站管理员" value="3"></el-option>
                <el-option label="环保管理部门" value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工作单位" label-width="80px" prop="profession">
              <el-input
                v-model="addedForm.profession"
                placeholder="工作单位"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职业" prop="technicalTitle">
              <el-input
                v-model="addedForm.technicalTitle"
                placeholder="职业"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-row class="experience">
          <div class="subTit">
            从业经历
            <span>
              <el-button class="greenBtn" size="mini" @click="addInput('innerMap', ['startTime', 'endTime', 'company'])">新增一项</el-button>
              <el-button size="mini" @click="delInput('innerMap')">删除</el-button>
            </span>
          </div>
          <p v-for="(item, index) of addedForm.experienceTemp.innerMap" :key="index">
            <el-col :span="14">
              <el-form-item label="时间" label-width="80px">
                <el-col :span="11">
                  <el-date-picker
                    v-model="item.startTime"
                    type="date"
                    :clearable="false"
                    style="width: 100%"
                    value-format="yyyy-MM-dd"
                    placeholder="选择开始日期">
                  </el-date-picker>
                </el-col>
                <el-col :span="2" class="line"> - </el-col>
                <el-col :span="11">
                  <el-date-picker
                    v-model="item.endTime"
                    type="date"
                    :clearable="false"
                    style="width: 100%"
                    value-format="yyyy-MM-dd"
                    placeholder="选择结束日期">
                  </el-date-picker>
                </el-col>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="工作单位" label-width="80px">
                <el-input v-model="item.company" placeholder="工作单位"></el-input>
              </el-form-item>
            </el-col>
          </p>
        </el-row> -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="绑定街道" label-width="80px" prop="streetId">
              <el-select
                v-model="addedForm.streetId"
                style="width: 100%"
                @change="selectStreetChange"
              >
                <el-option
                  v-for="street in streetList"
                  :key="street.streetId"
                  :label="street.streetName"
                  :value="street.streetId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="短信通知" prop="informemethod">
              <el-radio-group v-model="addedForm.informemethod">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="验证码" prop="kaptcha">
              <el-input
                placeholder="请输入验证码"
                v-model="addedForm.kaptcha"
                autocomplete="off"
              >
                <template slot="append">
                  <el-button
                    class="code"
                    type="primary"
                    v-show="show"
                    @click.prevent="getCode(addedForm.phone)"
                    >获取验证码</el-button
                  >
                  <el-button type="info" v-show="!show"
                    >{{ count }}s后重试</el-button
                  >
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item
          label="上传头像"
          label-width="80px"
          style="margin-top: 20px"
        >
          <el-upload
            ref="uploadPhoto"
            action=""
            :file-list="addedForm.photoList"
            list-type="picture-card"
            multiple
            :limit="1"
            :on-change="uploadChange"
            :on-exceed="uploadExceed"
            :http-request="handleSubmit"
            :auto-upload="false"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label-width="80px">
          <el-button
            type="primary"
            class="greenBtn"
            size="mini"
            @click="addedSubmit"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { mapActions, mapMutations } from "vuex";
import posts from "@/plugins/request.js";
import storage from "@/plugins/localStorage";
import { systemRoleAction, gekaptcha } from "@/http/api";
import Crypto from "@/utils/crypto";
export default {
  name: "login",
  data() {
    return {
      roleArr: [], //角色数组
      msg: "hello login!",
      loading: false,
      account: "",
      password: "",
      forgetPassWordVisible: false,
      forgetPassWordLoading: false,
      forgetPassWordForm: {
        account: "",
        phone: "",
        identity: "",
        newPassword: "",
      },
      forgetFormRules: {
        account: [
          {
            required: true,
            message: "请输入账号",
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
        ],
        kaptcha: [
          {
            required: true,
            message: "请输入验证码",
            trigger: "blur",
          },
        ],
        identity: [
          {
            required: true,
            message: "请输入身份证",
            trigger: "blur",
          },
        ],
        newPassword: [
          {
            required: true,
            message: "请输入新密码",
            trigger: "blur",
          },
        ],
      },
      addedFormVisible: false,
      addedFormLoading: false,
      addFormData: {},
      addedForm: {
        birth: "", //出生日期
        gender: "", //性别 0女 1男
        identity: "", //身份证
        phone: "", //手机号
        profession: "", //单位
        roleId: "", //角色类型id
        school: "", //毕业院校
        technicalTitle: "", //职业
        username: "", //姓名
        photoList: [], //头像
        kaptcha: "", //验证码
        experienceTemp: {
          //从业经历
          innerMap: [
            {
              startTime: "",
              endTime: "",
              company: "",
            },
          ],
        },
        streetId: "", //绑定街道，
        informemethod: 0, //是否短信通知
      },
      addedFormRules: {
        username: [
          {
            required: true,
            message: "请填写姓名",
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            message: "请填写手机号",
            trigger: "blur",
          },
        ],
        gender: [
          {
            required: true,
            message: "请选择性别",
            trigger: "change",
          },
        ],
        birth: [
          {
            type: "string",
            required: true,
            message: "请选择时间",
            trigger: "change",
          },
        ],
        school: [
          {
            required: true,
            message: "请填写毕业院校",
            trigger: "blur",
          },
        ],
        profession: [
          {
            required: true,
            message: "请填写单位",
            trigger: "blur",
          },
        ],
        technicalTitle: [
          {
            required: true,
            message: "请选择专业",
            trigger: "change",
          },
        ],
        identity: [
          {
            required: true,
            message: "请填写身份证",
            trigger: "blur",
          },
        ],
        roleId: [
          {
            required: true,
            message: "请选择角色类型",
            trigger: "change",
          },
        ],
        photoList: [
          {
            required: true,
            message: "请选择头像",
            trigger: "change",
          },
        ],
        streetId: [
          {
            required: true,
            message: "请选择绑定街道",
            trigger: "change",
          },
        ],
        informemethod: [
          {
            required: true,
            message: "请选择选项",
            trigger: "change",
          },
        ],
      },
      streetList: [],
      //初始值
      show: true,
      count: "",
    };
  },
  created() {
    storage.reload();
    this.resetHeaderTips();
    if (window.myWebsocket) {
      window.myWebsocket.close();
    }
    this.systemRole();
  },
  methods: {
    // 获取短信验证码
    getCode(phone) {
      if (this.validatePhone(phone)) {
        this.vaTime();
        let params = { phone: phone };
        console.log("params", params);
        gekaptcha(params)
          .then((res) => {
            if (res.code === 200) {
              this.$message({
                message: "验证码已发送成功",
                type: "success",
              });
            }
          })
          .catch((error) => {
            console.log(error);
          });
      }
    },

    // 验证码倒计时
    vaTime() {
      this.count = 120;
      this.show = false;
      let timer = 0;
      timer = setInterval(() => {
        if (this.count > 0 && this.count <= 120) {
          this.count--;
        } else {
          this.show = true;
          clearInterval(timer);
          timer = 0;
        }
      }, 1000);
    },
    // 判断手机号是否合法
    validatePhone(phone) {
      if (!phone) {
        this.$message({
          message: "手机号码不能为空",
          type: "error",
        });
      } else if (!/^1[3|4|5|7|8][0-9]\d{8}$/.test(phone)) {
        this.$message({
          message: "请输入正确是手机号",
          type: "error",
        });
      } else {
        return true;
      }
    },

    //角色数据
    systemRole() {
      systemRoleAction().then((res) => {
        this.roleArr = res.data.map(({ description, id }) => ({
          description,
          id,
        }));
      });
    },
    ...mapActions(["login", "putForgetPassword", "postUserRegister"]),
    ...mapMutations([
      "updateUserInfo",
      "updateUserToken",
      "updatePageTree",
      "resetHeaderTips",
      "changeWarningWay",
    ]),
    openForgetPwCnt() {
      this.forgetPassWordForm.account = this.account;
      this.forgetPassWordVisible = true;
    },
    subForgetPassword(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.forgetPassWordLoading = true;
          let forgetPassWordForm = this.forgetPassWordForm;
          let result = await this.putForgetPassword(forgetPassWordForm);
          if (result.message !== "success") {
            this.$notify({
              type: "warning",
              title: "提示",
              message: result.info,
            });
          } else {
            this.$notify({
              type: "success",
              title: "成功",
              message: "修改成功！！",
            });
            this.$refs[formName].resetFields();
            this.forgetPassWordVisible = false;
            this.show = true;
            this.count = "";
          }
          this.forgetPassWordLoading = false;
          this.show = true;
          this.count = "";
        } else {
          return false;
        }
      });
    },
    openWarnNotify(msg) {
      this.$notify({
        title: "警告",
        message: msg,
        type: "warning",
      });
    },
    //登陆请求
    async doLogin() {
      this.loading = true;
      let account = Crypto.encrypt(this.account);
      let password = Crypto.encrypt(this.password);
      let result = await this.login({
        account: account,
        password: password,
      });
      if (result.message === "success") {
        storage.set("userInfo", result); //个人信息及左侧列表信息存储
        this.updateUserInfo(result.data);
        this.updateUserToken(result.data.token);
        let trees = result.data.trees.children;
        this.updatePageTree(trees);
        this.$notify({
          title: "成功",
          message: "登录成功！",
          type: "success",
        });
        // trees[0].children[0].url
        await posts.getUserOnline().then(() => {
          this.changeWarningWay(result.data.user.pcinforme || 0);
          // if(trees[1].url && trees[1].url == '/stationMonitor'){
          // 	this.$router.push(trees[1].url)
          // }else{
          // 	this.$router.push(trees[0].children[0].url)
          // }
          if (trees[0].children) {
            this.$router.push(trees[0].children[0].url);
          } else {
            this.$router.push(trees[0].url);
          }
        });
      } else {
        this.loading = false;
        this.openWarnNotify(result.info);
      }
    },
    deepTraversal(trees) {
      let nodes = [];
      (function dfs(node) {
        let nodeLen = node.length;
        for (let i = 0; i < nodeLen; i++) {
          if (node[i].children) {
            dfs(node[i].children);
          } else {
            nodes.push(node[i]);
          }
        }
      })(trees);
      return nodes;
    },
    //注册提交
    addedSubmit() {
      this.$refs["addedForm"].validate(async (valid) => {
        if (valid) {
          // if(this.addedForm.photoList.length > 0) {
          this.addedFormLoading = true;
          this.addFormData = new FormData();
          let addedForm = this.addedForm;
          this.$refs.uploadPhoto.submit();
          for (let i in addedForm) {
            this.loopAppend(this.addFormData, i, addedForm[i]);
          }
          this.addFormData.append(
            "experienceTemp",
            JSON.stringify(addedForm.experienceTemp)
          );
          let result = await this.postUserRegister(this.addFormData);
          if (result.message !== "success") {
            this.$notify({
              type: "warning",
              title: "提示",
              message: result.info,
            });
          } else {
            this.$notify({
              type: "success",
              title: "成功",
              message: "申请成功！！请等待管理员审核。",
            });
            this.$refs["addedForm"].resetFields();
            this.addedFormVisible = false;
          }
          this.addedFormLoading = false;
          // }else {
          //   this.$notify.warning({
          //     title: '警告',
          //     message: '最少上传1张图片',
          //   })
          // }
        } else {
          return false;
        }
      });
    },
    async added() {
      this.addedFormVisible = true;
      const { data } = await posts.getStreetMessage();
      this.streetList = data;
    },
    loopAppend(formData, key, value) {
      if (key != "experienceTemp" && key != "photoList") {
        formData.append(key, value);
      }
    },
    uploadChange(file, fileList) {
      this.addedForm.photoList = fileList;
    },
    uploadExceed() {
      this.$notify.warning({
        title: "警告",
        message: "最多上传1张头像",
      });
    },
    handleSubmit(response) {
      this.addFormData.append("photos", response.file);
    },
    addInput(key, newInput) {
      let group = this.addedForm.experienceTemp[key];
      let newitem = {};
      newInput.map((item) => {
        newitem[item] = "";
      });
      group.push(newitem);
    },
    delInput(key) {
      let group = this.addedForm.experienceTemp[key];
      if (group.length > 1) {
        group.splice(-1);
      }
    },
    selectStreetChange() {
      // let isAll = val.find(v => v.streetName === "全区")
    },
  },
  beforeCreate() {},
};
</script>
<style scoped>
.code {
  background: #66b1ff !important;
  border-color: #66b1ff !important;
  color: #fff !important;
}

.loginCnt {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: #1260ff;
  background-image: linear-gradient(140deg, #30bcfc 0%, #1260ff 100%),
    linear-gradient(#30bcfc, #1260ff);

  overflow: hidden;
}

.box {
  position: relative;
  top: 45%;
  display: flex;
  /* flex-direction: row; */
  align-items: center;
  /* justify-content: space-between; */
  width: 1100px;
  height: 474px;
  margin: 0 auto;
  margin-top: -237px;
  /* background: #0251d9; */
  transition: 0.3s ease-in-out;
  z-index: 1;
  padding-left: 12%;
}

.box .img {
  position: absolute;
  bottom: 0px;
  height: 100%;
  width: 50%;
}

.box .img img {
  height: 100%;
  /* width: 100%; */
}

.box .line {
  position: absolute;
  top: 20%;
  width: 1px;
  height: 74%;
  background-color: #fff;
  left: 50%;
}

.box .inputBox {
  position: absolute;
  top: 0;
  box-sizing: border-box;
  width: 420px;
  right: 11%;
  padding: 5% 30px;
  /* height: 100%; */
}

.box .inputBox::after {
  content: "";
  background: red;
}

.box .inputBox h3 {
  letter-spacing: 2px;
  color: #fff;
  text-align: center;
  font-weight: 600;
  margin-bottom: 30px;
  font-size: 28px;
  line-height: 42px;
}

.inputBox .loginBtn {
  text-align: center;
  margin-top: 20px;
  width: 100%;
  line-height: 40px;
  height: 40px;
  background-color: #fff;
  border-radius: 27px;
  color: #1286ff;
  box-shadow: 0px 5px 15px 0px rgba(78, 78, 78, 0.4);
  cursor: pointer;
  transition: background-color 0.3s ease-in-out;
}

.inputBox .loginBtn:hover {
  background-color: #1362ff;
  color: #fff;
}

.inputBox .footerBtn {
  width: 100%;
  height: 26px;
  line-height: 26px;
  margin: 20px 0 12px 0;
  display: flex;
  justify-content: space-between;
}

.inputBox .footerBtn .forgetPassword {
  text-decoration: underline;
  color: #fff;
  cursor: pointer;
  float: right;
}

.inputBox .input {
  width: 90%;
  margin: 0 auto;
}

@media (min-width: 1600px) {
  .box {
    width: 1000px;
    padding-left: 0;
    /* margin-top: 240px; */
  }

  .box .line {
    left: 49%;
  }

  .box .inputBox {
    width: 420px;
    right: 0;
    padding: 6% 30px;
  }
}

.box .tips {
  width: 100%;
  text-align: center;
  position: absolute;
  line-height: 26px;
  background: #3f3d56;
  top: -26px;
  left: 0;
  color: #fff;
  border-radius: 4px 4px 0 0;
}

.box .tips a {
  color: #fff;
  text-decoration: underline;
}

.experience .line {
  text-align: center;
}

.experience {
  margin-top: 20px;
}

.experience .subTit {
  font-size: 18px;
  color: #444;
  line-height: 44px;
  margin-bottom: 15px;
}

.footer {
  position: absolute;
  width: 100%;
  bottom: 0;
  text-align: center;
  color: #eee;
  font-size: 12px;
}
</style>
<style>
.loginCnt .el-dialog__header {
  background-image: linear-gradient(90deg, #4eb2ff 0%, #0b69cb 100%),
    linear-gradient(#1e87f0, #1e87f0);
  padding: 20px;
  color: #fff;
}

.loginCnt .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}
</style>
